package org.kommii.appEncryption;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;


public class RSAHandlerAppUtil {
	
    
    /**
     * 将字符创还原为公钥对
     * @param str
     * @return
     */
    public static PublicKey decodePublicKeyFromString(String str) {
        String[] arr = str.split(" ");
        BigInteger modulus = new BigInteger(1, decode(arr[0]));
        BigInteger publicExponent = new BigInteger(1,decode(arr[1]));
        RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus,publicExponent);
        KeyFactory keyf;
        try {
            keyf = KeyFactory.getInstance("RSA");
            return keyf.generatePublic(rsaPubKey);
        } catch (Exception e) {
            return null;
        }
    }
    
   
    
    /**
     * 用公钥加密
     * @param data
     * @param pubKey
     * @return
     */
    public static byte[] encryptDataByPubKey(byte[] data, PublicKey pubKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 用公钥解密
     * @param data
     * @param pubKey
     * @return
     */
    public static byte[] decryptDataByPubKey(byte[] data, PublicKey pubKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }
    
    
   	  public static String encode(byte[] byteArray) {
   		  	
//   		  	sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
//   			base64Encoder.encode(byteArray);
   	        return Base64.encodeBase64String(byteArray);
   	    }

   	  public static byte[] decode(String base64EncodedString) {
//   	        sun.misc.BASE64Decoder base64Decoder = new sun.misc.BASE64Decoder();
   	        try {
//   	            return base64Decoder.decodeBuffer(base64EncodedString);
   	        	return Base64.decodeBase64(base64EncodedString);
   	        } catch (Exception e) {
   	            return null;
   	        }
   	    }
   	   
   
    
    public static void main(String[] args){
    	//公钥字符串
    	String str = "AKbF8mfBSNRnxq19QkpPvPnS5vnIqIivJdCvNWwIbhTquVUCVqM5MVBfPHoJncVc9mn6xoUtXKvJOlLSopPxe1M= AQAB";
    	PublicKey pubk = decodePublicKeyFromString(str);
    	
    	String ss = "2015-02-13 15:15:09";
		System.out.println(ss);
    	byte[] by = ss.getBytes();
    	
    	byte[] rs =  encryptDataByPubKey(by,pubk);
    	str = rs.toString();
    	System.out.println(new String(rs));
    	
    }

}
